<template>
  <a-modal v-model="visible" :title="title" :confirmLoading="submitLoading" width="600px" ok-text="确认" cancel-text="取消"
    @ok="addFormSubmit" :footer="!isUpdate ? undefined : null">
    <a-form :form="events_form" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }">
      <a-form-item label="内容类型">
        <a-select v-model="jobType" placeholder="选择类型">
          <a-select-option :key="1">
            工作量确认
          </a-select-option>
          <a-select-option :key="2">
            工资确认
          </a-select-option>
        </a-select>
      </a-form-item>
      <div v-if="isUpdate">
        <a-alert message="填写导入数据信息：请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除" type="info" />
        <a-button type="primary" @click="downloadCreate" ghost style="display: block;margin: 20px auto;width: 160px;">下载模板</a-button>
        <a-alert message="上传填好的信息表：文件后缀名必须为xls 或xlsx （即Excel格式），文件大小不得大于10M，最多支持导入3000条数据" type="info" />
        <a-button @click="uploadFile()" type="primary" style="display: block;margin: 20px auto;width: 160px;">点击上传文件</a-button>
        <input type="file" ref="uploadFileRef" @change="handleFileChange" style="display: none;" />
      </div>
      <div v-else>
        <a-form-item label="企业" v-if="userInfo.type == 4">
          <a-select v-model="enterpriseId" @change="enterpriseChange" placeholder="选择企业">
            <a-select-option v-for="item in enterpriseData" :key="item.enterpriseId" :name="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="残疾人姓名">
          <a-input placeholder="请输入残疾人姓名" v-decorator="['disabledName']"></a-input>
        </a-form-item>
        <a-form-item label="身份证号">
          <a-input placeholder="请输入身份证号" v-decorator="['idCard']"></a-input>
        </a-form-item>
        <a-form-item label="年月">
          <a-month-picker @change="handleRangeChange" format="YYYY-MM"
            v-decorator="['generationTime']"></a-month-picker>
        </a-form-item>
        <div v-if="jobType == 1">
          <a-form-item label="月内第几周">
            <a-select v-decorator="['weekNum']" placeholder="请选择月内第几周">
              <a-select-option key="第一周">
                第一周
              </a-select-option>
              <a-select-option key="第二周">
                第二周
              </a-select-option>
              <a-select-option key="第三周">
                第三周
              </a-select-option>
              <a-select-option key="第四周">
                第四周
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="工作岗位">
            <a-input placeholder="请输入工作岗位" v-decorator="['position']"></a-input>
          </a-form-item>
          <a-form-item label="工作内容">
            <a-input placeholder="请输入工作内容" v-decorator="['businessContent']"></a-input>
          </a-form-item>
          <a-form-item label="工作要求">
            <a-input placeholder="请输入工作要求" v-decorator="['requirement']"></a-input>
          </a-form-item>
          <a-form-item label="完成情况">
            <a-input placeholder="请输入完成情况" v-decorator="['completionStatus']"></a-input>
          </a-form-item>
          <a-form-item label="得分">
            <a-input placeholder="请输入得分" v-decorator="['score']"></a-input>
          </a-form-item>
        </div>
      </div>

      <!-- <a-form-item label="文件上传" style="width: 100%;">
        <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;" v-if="pdfUrls">
          <a :href="pdfUrls" target="_blank" style="line-height: 1.5;">{{ strSlice(pdfUrls) }}</a>
          <a @click="delFileUpload()" style="flex-shrink: 0;">删除</a>
        </div>
        <div v-else>
          <a-button @click="uploadFile()" type="primary">点击上传文件</a-button>
          <input type="file" ref="uploadFileRef" @change="handleFileChange" style="display: none;" />
        </div>
      </a-form-item> -->
      <!-- <a-form-item label="图片">
        <span v-if="imgUrls?.length > 0">
          <div v-for="(item, index) in imgUrls" :key="index" class="uploadDiv">
            <img :src="item" alt="" />
            <a-icon type="close-circle" theme="filled" class="iconClose" @click="delImgUpload(index)" />
          </div>
        </span>
        <div class="uploadDiv" @click="uploadImg"><a-icon type="plus" style="font-size: 32px;" /></div>
        <input type="file" ref="uploadImgRef" @change="handleImgChange" style="display: none;" />
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>

<script>
import {
  addDisabledJobConfirmation,
  updateJobConfirmation,
  downloadConfirmationFromTemplate,
  excelImportConfirmationData
} from "@/api/human/disabled"
import {
  getListEnterprise
} from '@/api/human/department'
import { uploadNewFile } from "@/api/manage/base"
import moment from 'moment';
import store from '@/store'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'AddInfo',
  data() {
    return {
      title: "",
      visible: false,
      submitLoading: false,

      id: "",
      enterpriseId: "", // 企业id
      enterpriseData: [], // 企业列表
      jobType: 1,
      generationTime: "",
      imgUrls: [], // 图片数组
      pdfUrls: "", // 文件数据

      isUpdate: false, // 是否上传
    }
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    });
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    moment,
    // 打开编辑弹窗 
    async add(row, update) {
      this.visible = true;
      this.imgUrls = [];
      this.pdfUrls = "";
      this.generationTime = "";
      this.id = row === true ? '' : row.id;
      this.isUpdate = update ? true : false;
      if (this.userInfo.type == 4) {
        // hr管理端
        this.getEnterpriseData(row.enterpriseId);
      } else if (this.userInfo.type == 5) {
        // hr企业端
        this.enterpriseId = row.enterpriseId;
      }
      if (row == true) {
        this.title = '新增';
        this.$nextTick(() => {
          this.events_form.resetFields();
        })
      } else {
        this.title = '修改';
        this.$nextTick(() => {
          let values = this.events_form.getFieldsValue();
          for (var key in row) {
            values[key] = row[key]
          }
          this.jobType = row['jobType'] || 1;
          this.generationTime = row['generationTime'] || "";
          this.imgUrls = row['imgUrls'] || [];
          this.pdfUrls = row['pdfUrls'] || "";
          this.events_form.setFieldsValue(values);
        })
      }
    },
    // 名称截取
    strSlice(str) {
      const spliceLength = str.lastIndexOf("/");
      return str.slice(spliceLength + 1);
    },
    // 日期选择
    handleRangeChange(value, mode) {
      this.generationTime = value ? moment(value).format("YYYY-MM") : null;
    },
    // 图片上传
    uploadImg() {
      this.$refs.uploadImgRef.click()
    },
    async handleImgChange(e, filed) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) { return; }
      if (file.type.indexOf('image') === -1) {
        _this.$message.error("非法图片格式");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 1)) {
        _this.$message.error('图片大小不能超过 1MB!')
        e.target.value = "";
        return;
      }
      var params = new FormData();
      params.append("file", file);
      params.append("dirName", '工作内容确认');
      let { code, data } = await uploadNewFile(params);
      if (code == '1') {
        _this.imgUrls.push(data);
        e.target.value = "";
      }
    },
    // 删除图片
    delImgUpload(i) {
      this.imgUrls.splice(i, 1);
    },
    // 获取客户员工
    async getEnterpriseData(id) {
      getListEnterprise({
        disabledType: 1
      }).then(res => {
        if (res.code === '1') {
          this.enterpriseData = res.data;
          if (id) {
            this.enterpriseId = id;
          } else {
            this.enterpriseId = this.enterpriseData[0].enterpriseId;
          }
        }
      })
    },
    // 选择客户
    enterpriseChange(value) {
      this.enterpriseId = value
    },
    // 下载模板
    downloadCreate() {
      downloadConfirmationFromTemplate({
        templateType: this.jobType
      }).then(res => {
        const blob = new Blob([res]);
        const fileName = this.jobType == 1 ? '工作量确认模板.xlsx' : '工资确认模板.xlsx';
        const elink = document.createElement('a'); // 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click(); // 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink); // 释放标签
      })
    },
    // 文件上传
    uploadFile() {
      this.$refs.uploadFileRef.click()
    },
    async handleFileChange(e, filed) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) { return; }
      if (!(file.size / 1024 / 1024 < 10)) {
        _this.$message.error('文件大小不能超过 10MB!')
        e.target.value = "";
        return;
      }
      var params = new FormData();
      params.append("file", file);
      params.append("templateType", this.jobType);
      let { code, data } = await excelImportConfirmationData(params);
      e.target.value = "";
      if (code == '1') {
        this.$emit('on-ok');
      }
    },
    // 删除文件
    delFileUpload(i) {
      this.pdfUrls = "";
    },
    // 提交
    async addFormSubmit() {
      this.events_form.validateFieldsAndScroll(async (err, values) => {
        if (!err) {
          if (this.id) {
            // 修改
            values.id = this.id;
          } else {
            // 新增
          }
          values.jobType = this.jobType;
          values.enterpriseId = this.enterpriseId;
          values.generationTime = this.generationTime;
          values.imgUrls = this.imgUrls;
          values.pdfUrls = this.pdfUrls;
          this.submitLoading = true;
          const { code } = this.id ? await updateJobConfirmation(values) : await addDisabledJobConfirmation(values);
          this.submitLoading = false;
          if (code === '1') {
            this.visible = false;
            this.$message.success('操作成功');
            this.$emit('on-ok');
          }
        }
      });
    }
  }
}
</script>
